<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
declare (strict_types = 1);
namespace app\api\controller;

use app\api\BaseController;
use app\api\middleware\Auth;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use think\facade\Request;
use app\home\validate\UserCheck;
use think\facade\Session;
use avatars\MDAvatars;
class User
{
    /**
     * 控制器中间件 [登录、注册 不需要鉴权]
     * @var array
     */
	protected $middleware = [
    	Auth::class => ['except' 	=> ['index','login','user_login'] ]
    ];
    /**
     * jwt配置
     * @var string
     */
    public $jwt_conf = [
        'secrect' => 'nongke',
        'iss' => 'xintongyun.ltd', //签发者 可选
        'aud' => 'nongke', //接收该JWT的一方，可选
        'exptime' => 720000, //过期时间,这里设置2个小时
    ];
    /**
     * @param $user_id
     * @return string
     */
    public function getToken($user_id){
        $time = time(); //当前时间
		$conf = $this->jwt_conf;
        $token = [
            'iss' => $conf['iss'], //签发者 可选
            'aud' => $conf['aud'], //接收该JWT的一方，可选
            'iat' => $time, //签发时间
            'nbf' => $time-1 , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time+$conf['exptime'], //过期时间,这里设置2个小时
            'data' => [
                //自定义信息，不要定义敏感信息
                'userid' =>$user_id,
            ]
        ];
        return JWT::encode($token, $conf['secrect'], 'HS256'); //输出Token  默认'HS256'
    }

    /**
     * @param $token
     */
    public static function checkToken($token){
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, self::$config['secrect'], ['HS256']); //HS256方式，这里要和签发的时候对应
            return (array)$decoded;
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            return json(['code'=>403,'msg'=>'签名错误']);
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return json(['code'=>401,'msg'=>'token失效']);
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            return json(['code'=>401,'msg'=>'token已过期']);
        }catch(Exception $e) {  //其他错误
            return json(['code'=>404,'msg'=>'非法请求']);
        }catch(\UnexpectedValueException $e) {  //其他错误
            return json(['code'=>404,'msg'=>'非法请求']);
        } catch(\DomainException $e) {  //其他错误
            return json(['code'=>404,'msg'=>'非法请求']);
        }

    }	
	
    /**
     * @api {post} /demo/login 会员登录
     * @apiDescription 系统登录接口，返回 token 用于操作需验证身份的接口

     * @apiParam (请求参数：) {string}             username 登录用户名
     * @apiParam (请求参数：) {string}             password 登录密码

     * @apiParam (响应字段：) {string}             token    Token

     * @apiSuccessExample {json} 成功示例
     * {"code":0,"msg":"登录成功","time":1627374739,"data":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkuZ291Z3VjbXMuY29tIiwiYXVkIjoiZ291Z3VjbXMiLCJpYXQiOjE2MjczNzQ3MzksImV4cCI6MTYyNzM3ODMzOSwidWlkIjoxfQ.gjYMtCIwKKY7AalFTlwB2ZVWULxiQpsGvrz5I5t2qTs"}}
     * @apiErrorExample {json} 失败示例
     * {"code":1,"msg":"帐号或密码错误","time":1627374820,"data":[]}
     */
	
    public function login()
    {
        
        $param = get_params();
        if(empty($param['username'])){
            return to_assign(1,'用户名不能为空');
        }
        if(empty($param['password'])){
            return to_assign(1,'密码不能为空');
        }

        $admin = Db::name('Admin')->where(['username' => $param['username']])->find();
        //pr($admin,1);
        if (empty($admin)) {
            return to_assign(1, '用户名或手机号码错误');
        }
        $param['pwd'] = set_password($param['password'], $admin['salt']);
        //pr($admin['pwd'],1);echo "===";
        //pr($param['pwd']);
        if ($admin['pwd'] !== $param['pwd']) {
            return to_assign(1, '用户或密码错误');
        }
        if ($admin['status'] != 1) {
            return to_assign(1, '该用户禁止登录,请与管理者联系');
        }
        $data = [
            'is_lock' => 0,
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
            'login_num' => $admin['login_num'] + 1,
        ];
        Db::name('admin')->where(['id' => $admin['id']])->update($data);
        $session_admin = get_config('app.session_admin');
        Session::set($session_admin, $admin['id']);
        //$token = make_token();
        $token = $this->getToken($admin['id']);
        set_cache($token, $admin, 7200);
        $admin['token'] = $token;
        $logdata = [
            'uid' => $admin['id'],
            'type' => 'login',
            'action' => '登录',
            'subject' => '系统',
            'param_id'=>$admin['id'],
            'param'=>'[]',
            'ip' => request()->ip(),
            'create_time' => time()
        ];
        $retrunData['uid']=$admin['id'];
        $retrunData['token']=$token;
        $retrunData['thumb']=$admin['thumb'];
        $retrunData['nickname']=$admin['nickname'];
        Db::name('AdminLog')->strict(false)->field(true)->insert($logdata);
        return to_assign(200, '登录成功', $retrunData);
    }
   /**
     * 授权登录
     */ 
   public function user_login()
    {
        
        $param = get_params();
        if(empty($param['code'])){
            return to_assign(1,'code不能为空');
        }
        $appid = 'wx1083a98d85bc2c96';
        $appsecret = 'def3c898ee1b155653530cf39169fef0';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$param['code']."&grant_type=authorization_code";
        $action = file_get_contents($url);
        $arr = json_decode($action,true);
        if(isset($arr['errcode'])){
            //pr($arr);
            return to_assign($arr['errcode'], $arr['errmsg']);
            exit;
        }
        /*$arr['openid'] = 'oM6Nm5RteTy-aE5EFqKzIjHYvyCI';
        $arr['session_key'] = 'oM6Nm5RteTy-aE5EFqKzIjHYvyCI';*/
        $admin = Db::name('Admin')->where(['wechat_openid' => $arr['openid']])->find();
        //pr($admin);
        if (empty($admin)) {
            //注册新用户
            $param['wechat_openid'] = $arr['openid'];
            $param['create_time']=time();
            $param['type']=2;
            $param['did']=3;
            $param['nickname']='微信用户'.substr($arr['openid'], -6);
            $param['username']=$param['nickname'];
            $param['name']=$param['nickname'];
            $param['pwd']=$arr['openid'];
            $param['session_key']=$arr['session_key'];
            $param['salt']=$arr['openid'];
            //pr($param);
            $uid = Db::name('Admin')->strict(false)->field(true)->insertGetId($param);
            if (!isset($param['thumb']) || $param['thumb'] == '') {
                //$char = mb_substr($param['nickname'], 0, 1, 'utf-8');
                //$param['thumb'] =$this->to_avatars($char);
                $param['thumb'] ='/storage/avatars/default.png';
                Db::name('Admin')->where('id', $uid)->update(['thumb' => $param['thumb']]);
            }
            $param['id'] =$uid;
            $admin=$param;
            $login_num=1;
        }else{
            //登录
            //Db::name('Admin')->where('id', $admin['id'])->update(['thumb' => $this->to_avatars($char)]);
            //$uid = $admin['id'];
            $login_num=$admin['login_num'] + 1;
        }
        $data = [
            'is_lock' => 0,
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
            'login_num' => $login_num,
        ];
        //pr($admin);
        Db::name('admin')->where(['id' => $admin['id']])->update($data);
        $session_admin = get_config('app.session_admin');
        Session::set($session_admin, $admin['id']);
        //$token = make_token();
        $token = $this->getToken($admin['id']);
        set_cache($token, $admin, 7200);
        $admin['token'] = $token;
        $logdata = [
            'uid' => $admin['id'],
            'type' => 'login',
            'action' => '登录',
            'subject' => '系统',
            'param_id'=>$admin['id'],
            'param'=>'[]',
            'ip' => request()->ip(),
            'create_time' => time()
        ];
        $retrunData['uid']=$admin['id'];
        $retrunData['token']=$token;
        $retrunData['thumb']=$admin['thumb'];
        $retrunData['nickname']=$admin['nickname'];
        $retrunData['openid']=$arr['openid'];
        $retrunData['session_key']=$arr['session_key'];
        Db::name('AdminLog')->strict(false)->field(true)->insert($logdata);
        return to_assign(200, '登录成功', $retrunData);
        exit;

        
    }
    //生成头像
    public function to_avatars($char)
    {
        $defaultData = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾',
            '一', '二', '三', '四', '五', '六', '七', '八', '九', '十');
        if (isset($char)) {
            $Char = $char;
        } else {
            $Char = $defaultData[mt_rand(0, count($defaultData) - 1)];
        }
        $OutputSize = min(512, empty($_GET['size']) ? 36 : intval($_GET['size']));

        $Avatar = new MDAvatars($Char, 256, 1);
        $avatar_name = '/avatars/avatar_256_' . set_salt(10) . time() . '.png';
        $path = get_config('filesystem.disks.public.url') . $avatar_name;
        $res = $Avatar->Save('.' . $path, 256);
        $Avatar->Free();
        return $path;
    }
    
    public function logout(){
        $session_admin = get_config('app.session_admin');
        if (!Session::has($session_admin)) {
            $this->apiError('请先登录');
        }
        else{
            $this->uid = Session::get($session_admin);
            $login_admin = Db::name('Admin')->where(['id' => $this->uid])->find();
            $this->did = $login_admin['did'];
            Session::delete($session_admin);
            //pr($login_admin);
            return to_assign(200, '退出成功'); 
        }
        exit;
        //取出token值
       //$token=Jwt::getRequestToken();
       $token=$this->getToken($admin['id']);
       //查看缓存中是否有存在delete_token这个键
       $delete_token=cache('delete_token')?:[];
       //将token值放入delete_token数组中
       $delete_token[]=$token;
       // 将数组塞回缓存中
       cache('delete_t0ken',$delete_token);
       // 销毁成功
       return success();
 
   }
   //获取openid
    public function getOpenid(Request $request){
        $code = Request::post('code');
        if(!$code){
            $this->error("参数为空");
        }
        $appid = 'wx1083a98d85bc2c96';
        $appsecret = '2286bd000cbd8e41d668e51190668867';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $action = file_get_contents($url);
        $arr = json_decode($action,true);
        $result['code'] = '200';
        $result['openid'] = $arr['openid'];
        echo json_encode($result); 
        

        
    }
    //根据openid获取用户信息
    public function getUser(){
        $openid = Request::post('openid');
        if(!$openid){
            $this->error('未获取到openid');
        }
        $member = Member::where(['wechat_openid'=>$openid])->find();
        if($member){
            $this->success('成功',$member);
        }else{
            $this->error('失败');
        }
    }
    /**
     * @api {post} /index/demo 测试页面
     * @apiDescription  返回文章列表信息

     * @apiParam (请求参数：) {string}  token Token

     * @apiSuccessExample {json} 响应数据样例
     * {"code":1,"msg":"","time":1563517637,"data":{"id":13,"email":"test110@qq.com","password":"e10adc3949ba59abbe56e057f20f883e","sex":1,"last_login_time":1563517503,"last_login_ip":"127.0.0.1","qq":"123455","mobile":"","mobile_validated":0,"email_validated":0,"type_id":1,"status":1,"create_ip":"127.0.0.1","update_time":1563507130,"create_time":1563503991,"type_name":"注册会员"}}
     */
    public function test(Request $request)
    {
		$uid = JWT_UID;
        $userInfo = Db::name('Admin')->where(['id' => $uid])->find();
        $this->apiSuccess('请求成功', ['user' => $userInfo]);
    }
}
